package ysq.xyg.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yu sheng qiang
 * @create 2017-03-06 8:13
 **/
public class RedisUtill {
    private static Log log= LogFactory.getLog(RedisUtill.class);
    @Autowired
    private RedisTemplate redisTemplate;

    //单个添加
    public boolean add(final String key, final String value){
        return (Boolean) redisTemplate.execute(new RedisCallback() {
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<String> redisSerializer=redisTemplate.getStringSerializer();
                byte[] keys=redisSerializer.serialize(key);
                byte[] values=redisSerializer.serialize(value);
                return redisConnection.setNX(keys,values);
            }
        });
    }
    //多个添加
    public void addList(final Map<String,String> values){
        for (String s:values.keySet()){
            add(s,values.get(s));
        }
    }
    //单个删除
    public void delete(String key){
        List<String> list=new ArrayList<String>();
        list.add(key);
        deleteList(list);
    }
    //多个删除
    public void deleteList(List<String> keys){
        redisTemplate.delete(keys);
    }
    //修改或添加
    public boolean updateOrAdd(String key,String value){
        //if(redisTemplate.get(key))
        return (Boolean) redisTemplate.execute(new RedisCallback() {
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return null;
            }
        });
    }
    //获取
    public String get(final String key){
       return (String) redisTemplate.execute(new RedisCallback() {
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] keys = serializer.serialize(key);
                byte[] value = redisConnection.get(keys);
                if (value == null) {
                    return null;
                }
                return serializer.deserialize(value);
            }
        });
    }
}
